package com.wms.client;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.wms.tool.Contant;

/**
 * 
 * @author Created by YQR on 2018/2/2.
 *
 */
public class HttpClientBuild3false {
	private static Logger logger = LoggerFactory.getLogger(HttpClientBuild3false.class);

	private HttpClientBuild3false() {
	}

	public static JSONObject doPost(String path,String bodyParams) {
		CloseableHttpClient HttpClient=null;
	    HttpPost post=null;
	    StringEntity se=null;
	    HttpResponse res=null;
	    JSONObject response = null;
	    HttpEntity entity =null;
	    
	    try {
			// 创建客户端
			HttpClient = HttpClients.createDefault();
			// 请求行		
			post = new HttpPost(Contant.getProperties().get("URL")+path.toString());//通过配置文件读取url			
			post.addHeader("token",Contant.getProperties().getProperty("token"));			
			logger.debug("这里是请求行 ： {}", post);					
			// 请求实体			
			se = new StringEntity(bodyParams);
			se.setContentEncoding("UTF-8");
			se.setContentType("application/json");// 发送json数据需要设置contentType			
			post.setEntity(se);
			logger.debug("这里是实体  ： {}", bodyParams);
			// 响应行
			res = HttpClient.execute(post);
			logger.debug("这里是响应行 ： {}", res);

			if (res.getStatusLine().getStatusCode() == 200) {
				entity = res.getEntity();
				if (entity != null) {
					// 响应
					String result = EntityUtils.toString(entity,"UTF-8");//.toString(entity);
			        response = JSONObject.parseObject(result);//.parseObject(result);
					// 输出： response
					logger.debug("这里是响应  ：{}", response.toString());
					logger.debug("结束一次接口请求");
					return response;
					
				}
			} else {
				JSONObject reqFail = new JSONObject();			
				reqFail.put("code", res.getStatusLine().getStatusCode());
				reqFail.put("failbody", res.getStatusLine());
				logger.debug("关闭会话："+reqFail);
				return reqFail;
			}
			// 关闭流并释放资源
			HttpClient.close();
		} catch (Exception e) {
			logger.error("未能通过客户端{}", e.getMessage());
		}
		return null;
	}

}
